package logic

import (
	"context"
	"errors"
	"group-card/common/constant"
	"group-card/common/request"
	"group-card/model/entity"
	"group-card/rpc/card/cardclient"
	"group-card/rpc/card/internal/svc"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type BindingBoundLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBindingBoundLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BindingBoundLogic {
	return &BindingBoundLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// region TODO: 绑定 Author:LiuYanLin Date:2023/07/03 周一 15:41
func (l *BindingBoundLogic) BindingBound(in *cardclient.BindingBoundRequest) (*cardclient.BindingBoundResponse, error) {
	var ctx context.Context

	binding, err := l.svcCtx.BindingModel.FindOne(ctx, &entity.CardBindingReq{
		Id: in.Id,
	})
	if err != nil {
		return nil, err
	}
	if binding.Id == 0 {
		return nil, errors.New("卡片未发行")
	}
	if binding.Status != constant.CardBindingStatus10 || binding.UserId > 0 {
		return nil, errors.New("卡片已被绑定")
	}

	data := entity.CardBindingReq{
		Id:          in.Id,
		UserId:      in.UserId,
		BindingTime: time.Now(),
		Status:      constant.CardBindingStatus20,
		BaseReq: request.BaseReq{
			Columns: "user_id,binding_time,status",
		},
	}

	err = l.svcCtx.BindingModel.Update(ctx, &data)

	if err != nil {
		return nil, err
	}

	return &cardclient.BindingBoundResponse{}, nil
}

//endregion
